package com.toman.ui.work.workshop;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.BeltlineEntity;
import com.toman.JavaBean.OperationorderEntity;
import com.toman.JavaBean.PlanEntity;
import com.toman.JavaBean.SendworkOrderMappingEntity;
import com.toman.R;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.JsonUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.ToolBarActivity;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class PlanDispatchingActivity extends ToolBarActivity {
    PlanEntity bean;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.et_batch_number)
    EditText etBatchNumber;
    @BindView(R.id.et_stove_number)
    EditText etStoveNumber;
    @BindView(R.id.et_sendwork_count)
    EditText etSendworkCount;
    private List<OperationorderEntity> list = new ArrayList<>();
    private List<SendworkOrderMappingEntity> list2 = new ArrayList<>();
    CommonAdapter<OperationorderEntity> adapter;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plan_dispatching);
        ButterKnife.bind(this);
        initToolBar("派工");
        initIntetnt();
        initView();
        get();
    }

    private void initIntetnt() {
        bean = (PlanEntity) getIntent().getSerializableExtra("bean");

    }

    private void initView() {


//        OperationorderEntity
//SendworkOrderMappingEntity;
        initAdapter();
        lv.setAdapter(adapter);
//        adapter.notifyDataSetChanged();

    }

    private void initAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        lv.setLayoutManager(linearLayoutManager);


        adapter = new CommonAdapter<OperationorderEntity>(this, R.layout.item_plan_dispatching, list) {
            @Override
            protected void convert(ViewHolder holder, OperationorderEntity item, final int position) {
                holder.setText(R.id.tv_title, item.getOrderName());
                RecyclerView recyclerView = holder.getView(R.id.lv);
                item.setSendworkOrderMappingEntity(new ArrayList<>());

                SendworkOrderMappingEntity bean = new SendworkOrderMappingEntity();
                bean.setOrderId(item.getId());
                bean.setWorkCount(0L);
                item.getSendworkOrderMappingEntity().add(bean);
                BeltlineEntity beltlineEntity=new BeltlineEntity();
                beltlineEntity.setBeltlineName("请选择");
                item.getBeltlineEnties().add(0,beltlineEntity);
                Map map=new HashMap();

                CommonAdapter<SendworkOrderMappingEntity> adapter1 = new CommonAdapter<SendworkOrderMappingEntity>(getApplicationContext(), R.layout.item_plan_dispatching_more, item.getSendworkOrderMappingEntity()) {
                    @Override
                    protected void convert(ViewHolder holder, SendworkOrderMappingEntity item1, final int position) {
                        holder.setText(R.id.tv_name, item1.getBeltlineName());


                        holder.getView(R.id.iv_del).setOnClickListener(v -> remove(item.getSendworkOrderMappingEntity(), position, (CommonAdapter<SendworkOrderMappingEntity>) recyclerView.getAdapter(),map));
                        EditText editText = holder.getView(R.id.et_number);


                        ArrayAdapter<BeltlineEntity> adapter = new ArrayAdapter<BeltlineEntity>(getApplicationContext(), R.layout.dialog_item_beacon, item.getBeltlineEnties());
                        ;

                        Spinner spinner = holder.getView(R.id.sp);
                        spinner.setAdapter(adapter);

                        for (int i = 0; i < item.getBeltlineEnties().size(); i++) {
                            try {
                                if (item1.getBeltlineId()!=null){
                                if (item1.getBeltlineId().equals(item.getBeltlineEnties().get(i).getId())) {
                                    spinner.setSelection(i);
                                    break;
                                }}
                            } catch (Exception e) {

                            }
                        }

                        spinner.setSelected(false);
                        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position1, long id) {

                                BeltlineEntity entity = (BeltlineEntity) parent.getSelectedItem();
if (!entity.getBeltlineName().equals("请选择")) {
    if (map.containsKey(entity.getId())) {
        if (map.get(entity.getId()) != item1) {
            ToastUtil.error(getApplicationContext(), "同一工序不能重复选择产线");
            spinner.setSelection(0);
        }
    } else {
        item1.setBeltlineId(entity.getId());
        item1.setBeltlineName(entity.getBeltlineName());
        map.put(entity.getId(), item1);
    }
}


                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        BeltlineEntity selectedItem = null;
                        try {

                            selectedItem = (BeltlineEntity) spinner.getSelectedItem();
                          if (selectedItem==null){
                              ToastUtil.makeText(getApplicationContext(),"产线为空未配置或已被删除");
                              finish();
                          }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }
                        editText.addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                            }

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count) {

                            }

                            @Override
                            public void afterTextChanged(Editable s) {
                                if (!StringUtils.isEmpty(editText.getText().toString())) {
                                    item1.setWorkCount(Long.valueOf(editText.getText().toString()));
                                } else {
                                    item1.setWorkCount(0L);
                                }

                            }
                        });
                    }
                };
                recyclerView.setAdapter(adapter1);
                recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                adapter1.notifyDataSetChanged();
                holder.getView(R.id.iv_add).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SendworkOrderMappingEntity bean = new SendworkOrderMappingEntity();
                        bean.setOrderId(item.getId());
                        bean.setWorkCount(0L);
                        item.getSendworkOrderMappingEntity().add(bean);
                        adapter1.notifyItemInserted(item.getSendworkOrderMappingEntity().size());
                    }
                });
            }
        };
    }

    private void remove(List<SendworkOrderMappingEntity> listM, int position, CommonAdapter<SendworkOrderMappingEntity> adapter1, Map map) {
        if (listM.size() == 1) {
            ToastUtil.makeText(getApplicationContext(), "至少需要一条产线");
            return;
        }
        if (listM.get(position).getBeltlineId()!=null){
            map.remove(listM.get(position).getBeltlineId());}
            listM.remove(position);
        adapter1.notifyItemRemoved(position);
        adapter1.notifyItemRangeChanged(position, listM.size());
//        adapter1.notifyDataSetChanged();
    }

    public void get() {


        Map<String, Object> map = new HashMap<String, Object>();
        OkHttpUtils
                .get(NewBaseUrl.workshop_plan_getorderbeltlinesbyartlineid)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .params("artlineId", bean.getArtlineId() + "")
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", getClass().toString() + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {

                            List<OperationorderEntity> jsonArray = new ArrayList<>(JsonExcludeNull.parseArrayExcludeNull(jsonObj.getString("list"), OperationorderEntity.class));
                            list.addAll(jsonArray);
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }
                    }
                });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_finish, menu);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_finish:
                        add();
                        break;
                }
                return false;
            }
        });

        return true;
    }

    public void add() {
        List<SendworkOrderMappingEntity> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {

            for (int j = 0; j < list.get(i).getSendworkOrderMappingEntity().size(); j++) {
                SendworkOrderMappingEntity bean = list.get(i).getSendworkOrderMappingEntity().get(j);
                if (Long.valueOf(0L).equals(bean.getWorkCount())) {
                    ToastUtil.makeText(getApplicationContext(), "子派工单派工数量不得为0或空");
                    return;
                } else if(bean.getBeltlineId()==null){
                    ToastUtil.makeText(getApplicationContext(), "必须选择产线");
                    return;
                }

                else {
                    list1.add(bean);
                }
            }

        }
        if (etSendworkCount.getText().toString().equals("0")){
            ToastUtil.makeText(getApplicationContext(), "派工数量不得为0或空");
return;
        }
        ToastUtil.print(list1.toString());
        for (SendworkOrderMappingEntity entity : list1) {
            ToastUtil.print("名称" + entity.getBeltlineName() + "产线" + entity.getBeltlineId());
        }
        String[] item = new String[]{"派工日期", "计划完工日期", "派工数量"};//直接初始化

        if (ViewUtil.isNull(this, item, tvStartTime, tvEndTime, etSendworkCount)
                ) {
            return;
        }
        if (!TimeUtil.compareTwoTime3(tvStartTime.getText().toString(), tvEndTime.getText().toString())) {
            ToastUtil.makeText(getApplicationContext(), "完工日期必须晚于派工日期");
            return;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("artlineId", bean.getArtlineId() + "");
        map.put("sendworkDate", tvStartTime.getText().toString());
        map.put("completeworkDate", tvEndTime.getText().toString());
        map.put("planId", bean.getId());
        map.put("sendworkCount", etSendworkCount.getText().toString());
        map.put("mappings", list1);
        map.put("batchNumber", etBatchNumber.getText().toString());
        map.put("stoveNumber", etStoveNumber.getText().toString());

//        map.put("verifyScrappedCount", etScrappedCount.getText().toString());
//        map.put("verifyWasteCount", etWasteCount.getText().toString());
//        map.put("verifyRemakeCount", etRemakeCount.getText().toString());
//        map.put("verifyReuseCount", etReuseCount.getText().toString());


        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.workshop_plan_sendworkorder_save)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", getClass().toString() + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });

    }

    @OnClick({R.id.tv_start_time, R.id.tv_end_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_start_time:
                ViewUtil.getDate(this, tvStartTime);

                break;
            case R.id.tv_end_time:
                ViewUtil.getDate(this, tvEndTime);

                break;
        }
    }
}
